package com.tools.web.interceptor.auth;

import com.tools.common.object.json.JsonKit;
import com.tools.common.object.Note;
import com.tools.common.thread.Timeunit;
import com.tools.middle.redis.client.JedisPlus;
import com.tools.web.interceptor.access.AccessManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * 使用 JedisPlus 操作 Redis 单机客户端
 * 完成用户认证功能的管理器
 * */
@Note("使用 JedisPlus 操作 Redis 单机客户端" +
        "完成用户认证功能的管理器")
public final class SingleJedisPlusAuthenticationManager extends GenericAuthenticationManager {

    @Note("使用 JedisPlus 操作 Redis 单机客户端完成用户认证等操作")
    private final JedisPlus jedisPlus;

    @Note("日志对象")
    private static final Logger LOGGER = LoggerFactory.getLogger(SingleJedisPlusAuthenticationManager.class);

    /* **************************************************************************************
     *
     *          构造方法
     *
     * **************************************************************************************
     * */

    public SingleJedisPlusAuthenticationManager(JedisPlus jedisPlus, AuthSource source,
                                                AuthUserService authUserService) {
        this(jedisPlus, source, authUserService, null);
    }

    public SingleJedisPlusAuthenticationManager(JedisPlus jedisPlus, AuthSource source,
                                                AuthUserService authUserService, AccessManager accessManager) {
        super(source, authUserService, accessManager);
        this.jedisPlus = Objects.requireNonNull(jedisPlus);
    }

    /* **************************************************************************************
     *
     *          功能方法
     *
     * **************************************************************************************
     * */

    @Override
    protected Logger protected_getLogger() {
        return LOGGER;
    }

    @Override
    protected Timeunit protected_getTimeunitToBeUsed() {
        return Timeunit.SECOND;
    }

    @Override
    protected void protected_loginOut(String key, String deviceTypeId, String uuid,
                                      AuthUser authUser, String separator) {
        this.removeAuthUser(key);
    }

    @Override
    protected Res getAuthUser(String key, AuthToken token) {
        try {
            SingleAuthUser authUser = (SingleAuthUser) this.jedisPlus.get(key);
            if(authUser == null) return super.protected_getResIfExpired(token);
            if(Objects.equals(authUser.getUuid(), token.getUuid()) &&
                    Objects.equals(authUser.getDeviceTypeId(), token.getDeviceTypeId())) {
                return new Res(true, authUser);
            }
            return new Res(false, null);
        } finally {
            this.jedisPlus.close();
        }
    }

    @Override
    protected void setAuthUser(String key, AuthUser srcAuthUser, AuthToken token) {
        try {
            SingleAuthUser authUser = (SingleAuthUser) srcAuthUser;
            authUser.setUuid(token.getUuid());
            authUser.setDeviceTypeId(token.getDeviceTypeId());
            authUser.setUserType(token.getUserType());
            String json = JsonKit.toJSON(authUser);
            this.jedisPlus.setex(key, token.getExpiration(), json);
        } finally {
            this.jedisPlus.close();
        }
    }

    @Override
    protected void removeAuthUser(String key) {
        try {
            this.jedisPlus.del(key);
        } finally {
            this.jedisPlus.close();
        }
    }

    @Override
    protected void updateAuthUser(String key, AuthUser authUser, String separator) {
        try {
            String script = "local key = ARGV[1];" +
                            "local newValue = ARGV[2];" +
                            "if redis.call('exists', key) == 1 then" +
                            "    local ttl = redis.call('ttl', key);" +
                            "    redis.call('set', key, newValue);" +
                            "    if ttl > 0 then" +
                            "        redis.call('expire', key, ttl);" +
                            "    end" +
                            "    return 1;" +
                            "else" +
                            "    return 0;" +
                            "end";
            String json = JsonKit.toJSON(authUser);
            this.jedisPlus.eval(script, 0, key, json);
        } finally {
            this.jedisPlus.close();
        }
    }
}
